package com.jhd.fuzhou.service;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;

import com.jhd.fuzhou.util.CustomToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jp.co.canon.android.print.ij.sdk.CanonDiscoveryCallback;
import jp.co.canon.android.print.ij.sdk.CanonPrintCallback;
import jp.co.canon.android.print.ij.sdk.CanonPrintDevice;
import jp.co.canon.android.print.ij.sdk.CanonPrintDeviceBase;
import jp.co.canon.android.print.ij.sdk.CanonPrintJob;
import jp.co.canon.android.print.ij.sdk.CanonPrintParams;
import jp.co.canon.android.print.ij.sdk.CanonPrinterStatus;
import jp.co.canon.android.print.ij.sdk.CanonStatusCallback;
/*佳能打印机*/
public class PrinterService {
    private Context mContext;
    private static final int MSG_GET_STATUS = 1;
    private static final int MSG_STOP_DISCOVERY = 2;
    private ProgressDialog progressDialog;
    private final List<PrinterItem> mPrinterList = new ArrayList<>();
    private CanonPrintDeviceBase mSelectedPrinter;
    private CanonPrintJob mJob = createJob();
    private int mScaling = CanonPrintParams.SCALING_NONE;
    private int mPaperOrientation = CanonPrintParams.PAPERORIENTATION_AUTOMATIC;
    private Handler mHandler = new MyHandler();

    private PrinterService(Builder builder) {
        this.mContext = builder.mContext;
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setCanceledOnTouchOutside(false);
        discoveryPrinter();
    }
    /*搜索同一局域网的打印机*/
    public void discoveryPrinter(){
        CanonPrintDevice.startDiscovery(this.mContext, new CanonDiscoveryCallback() {
            @Override
            public void onFoundPrinter(final CanonPrintDeviceBase printer) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        PrinterItem item = new PrinterItem(printer);
                        mPrinterList.add(item);
                        Message msg = mHandler.obtainMessage(MSG_GET_STATUS, item);
                        mHandler.sendMessage(msg);
                    }
                });
            }
            @Override
            public void onFinished(boolean b) {
            }
        });
    }

    private static class PrinterItem {
        private CanonPrintDeviceBase device;
        private CanonPrinterStatus status;

        private PrinterItem(CanonPrintDeviceBase device) {
            this.device = device;
            this.status = null;
        }

        private void updateStatus() {
            this.device.getStatus(new CanonStatusCallback() {
                @Override
                public void onGotStatus(CanonPrinterStatus status) {
                    PrinterItem.this.status = status;
                }
            });
        }

        @Override
        public String toString() {
            if (this.status == null) {
                return this.device.getPrinterName();
            } else {
                return this.device.getPrinterName() + "(" + this.device.getDeviceHash()
                        + ") - Ready:" + this.device.isReadyDevice();
            }
        }
    }
    private void setSelectedPrinter(CanonPrintDeviceBase device) {
        mSelectedPrinter = device;
        if (mSelectedPrinter != null) {
            mJob.setDefaultPrintConfiguration(mContext, mSelectedPrinter);
            mJob.setPrintConfiguration(CanonPrintJob.Configuration.MediaType,1);
            mJob.setPrintConfiguration(CanonPrintJob.Configuration.PaperSize,3);
            mJob.setPrintConfiguration(CanonPrintJob.Configuration.Borderless,2);
            mJob.setPrintConfiguration(CanonPrintJob.Configuration.ColorMode,1);
            mJob.setPrintConfiguration(CanonPrintJob.Configuration.Duplex,1);
            mJob.setPrintConfiguration(CanonPrintJob.Configuration.Copies,1);
        } else {
            mJob = createJob();
        }
    }
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case MSG_GET_STATUS:
                    PrinterItem pi = (PrinterItem) message.obj;
                    pi.updateStatus();
                    break;
                case MSG_STOP_DISCOVERY:
                    CanonPrintDevice.stopDiscovery();
                    break;
            }
        }
    }
    private CanonPrintJob createJob() {
        CanonPrintJob job = new CanonPrintJob();
        if (mSelectedPrinter != null) {
            job.setDefaultPrintConfiguration(this.mContext, mSelectedPrinter);
        }
        return job;
    }

    public static final class Builder {
        private Context mContext;
        public Builder(Context val) {
            mContext = val;
        }
        public PrinterService build() {
            return new PrinterService(this);
        }
    }
    private void showToast(final String message) {
        CustomToast.showText(mContext,message,3000,0,0).show();
    }

    public void executePrint(Button button) {
        if(mPrinterList.size()==0){//判断是否搜索到打印机
            showToast("未搜索到打印机！");
            discoveryPrinter();
            return;
        }else{
            setSelectedPrinter(mPrinterList.get(0).device);
        }
        if (!mSelectedPrinter.isPrintableConfiguration(mJob)){//
            showToast("无效打印配置");
            return;
        }
        button.setClickable(false);
        String path=mContext.getExternalFilesDir(null).getPath()+ "/Download/document.pdf";
        File file=new File(path);
        mJob.setPrintFile(file, mPaperOrientation, mScaling);//设置打印任务
        mSelectedPrinter.print(mJob, new CanonPrintCallback() {
            @Override
            public void onChangedJobStatus(final CanonPrintJob job) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if(!progressDialog.isShowing()){
                            progressDialog.dismiss();
                            progressDialog.setMessage("打印中...");
                            progressDialog.show();
                        }
                        if (job.isFinished()) {
                            progressDialog.dismiss();
                            showToast("打印成功!");
                            button.setClickable(true);
                            mJob = createJob();
                        }
                    }
                });
            }
            @Override
            public void onChangedPrinterStatus(CanonPrintJob job, final CanonPrinterStatus status) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        //status.getStatus();
                    }
                });
            }
        });
    }
}